package org.jeecg.modules.demo.crm.controller;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.collection.CollUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.crm.entity.*;
import org.jeecg.modules.demo.crm.mapper.CInvoiceSplitMapper;
import org.jeecg.modules.demo.crm.mapper.CSubProjectMapper;
import org.jeecg.modules.demo.crm.service.ICCommonService;
import org.jeecg.modules.demo.crm.service.ICPaymentInvoiceService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

 /**
 * @Description: 收票登记
 * @Author: jeecg-boot
 * @Date:   2025-06-14
 * @Version: V1.0
 */
@Api(tags="收票登记")
@RestController
@RequestMapping("/crm/cPaymentInvoice")
@Slf4j
public class CPaymentInvoiceController extends JeecgController<CPaymentInvoice, ICPaymentInvoiceService> {
	@Autowired
	private ICPaymentInvoiceService cPaymentInvoiceService;
	 @Autowired
	 private CInvoiceSplitMapper cInvoiceSplitMapper;
	 @Autowired
	 private ICCommonService iCommonService;
	 @Autowired
	 private CSubProjectMapper cSubProjectMapper;
	/**
	 * 分页列表查询
	 *
	 * @param cPaymentInvoice
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "收票登记-分页列表查询")
	@ApiOperation(value="收票登记-分页列表查询", notes="收票登记-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<CPaymentInvoice>> queryPageList(CPaymentInvoice cPaymentInvoice,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		Boolean permissionCheck = iCommonService.permissionCheck();
		if(permissionCheck){
			//必须projectId subProjectId 都不能空
			if("-1".equals(cPaymentInvoice.getProjectId())){
				cPaymentInvoice.setProjectId(null);
			}
			if("-1".equals(cPaymentInvoice.getSubProjectId())){
				cPaymentInvoice.setSubProjectId(null);
			}
			/*if( StringUtils.isEmpty(cPaymentInvoice.getProjectId())
					&& StringUtils.isEmpty(cPaymentInvoice.getSubProjectId())) {
				if (StringUtils.isEmpty(cPaymentInvoice.getProjectId())) {
					cPaymentInvoice.setProjectId("-1");
				}
				if (StringUtils.isEmpty(cPaymentInvoice.getSubProjectId())) {
					cPaymentInvoice.setSubProjectId("-1");
				}
			}*/
		}

		Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
		customeRuleMap.put("paymentType", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("subProjectId", QueryRuleEnum.LIKE_WITH_OR);
		customeRuleMap.put("invoiceNumber", QueryRuleEnum.LIKE_WITH_OR);


		QueryWrapper<CPaymentInvoice> queryWrapper = QueryGenerator.initQueryWrapper(cPaymentInvoice, req.getParameterMap());
		queryWrapper.eq("del_flag", "0");

		if(permissionCheck){
			//如果不是管理员
			LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
			String subProjectId = cSubProjectMapper.subProjectPermissions(sysUser.getId());
			if(subProjectId == null){
				subProjectId = "-1";
			}
			List<Long> idList = Arrays.stream(subProjectId.split(","))
					.map(String::trim)
					.filter(StringUtils::isNotBlank)
					.map(Long::valueOf)
					.collect(Collectors.toList());
			queryWrapper.in("sub_project_id", idList);
		}

		Page<CPaymentInvoice> page = new Page<CPaymentInvoice>(pageNo, pageSize);
		IPage<CPaymentInvoice> pageList = cPaymentInvoiceService.page(page, queryWrapper);
		List<String> subProjectIds = pageList.getRecords()
				.stream()
				.map(CPaymentInvoice::getSubProjectId)   // YourEntity 换成你真实的实体类
				.filter(Objects::nonNull)           // 过滤 null
				.distinct()                         // 去重
				.collect(Collectors.toList());
		Map<String, CSubProject> spMap = new HashMap<>();
		if (!CollUtil.isEmpty(subProjectIds)) {    // hutool 的工具类，没有就换成 subProjectIds.isEmpty()
			List<CSubProject> subProjectList = cSubProjectMapper.selectBatchIds(subProjectIds);
			spMap = subProjectList.stream()
					.collect(Collectors.toMap(CSubProject::getId, Function.identity()));
		}

		Map<String, CSubProject> finalSpMap = spMap;
		pageList.getRecords().stream().forEach(e -> {
			//收款情况
			BigDecimal bigDecimal = cInvoiceSplitMapper.findbyInvoice(e.getId());
			List<CPaymentRequest> requestList = cInvoiceSplitMapper.findbyInvoiceQRequestId(e.getId());
			e.setPayment(bigDecimal);
			// 项目编号
			e.setProjectNumber(finalSpMap.get(e.getSubProjectId()).getProjectNumber());
			e.setRequestList(requestList);
		});



		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param cPaymentInvoice
	 * @return
	 */
	@AutoLog(value = "收票登记-添加")
	@ApiOperation(value="收票登记-添加", notes="收票登记-添加")
	@RequiresPermissions("crm:c_payment_invoice:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody CPaymentInvoice cPaymentInvoice) {
		cPaymentInvoice.setInvoiceStatus("待审核");
		cPaymentInvoiceService.add(cPaymentInvoice);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param cPaymentInvoice
	 * @return
	 */
	@AutoLog(value = "收票登记-编辑")
	@ApiOperation(value="收票登记-编辑", notes="收票登记-编辑")
	@RequiresPermissions("crm:c_payment_invoice:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody CPaymentInvoice cPaymentInvoice) {
		cPaymentInvoice.setInvoiceStatus("待审核");
		cPaymentInvoiceService.edit(cPaymentInvoice);
		return Result.OK("编辑成功!");
	}

	 /**
	  *  审核
	  *
	  * @param cPaymentInvoice
	  * @return
	  */
	 @AutoLog(value = "收票登记-审核")
	 @ApiOperation(value="收票登记-审核", notes="收票登记-审核")

	 @RequestMapping(value = "/audit", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> audit(@RequestBody CPaymentInvoice cPaymentInvoice) {
		 cPaymentInvoiceService.audit(cPaymentInvoice);
		 return Result.OK("审核成功!");
	 }
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "收票登记-通过id删除")
	@ApiOperation(value="收票登记-通过id删除", notes="收票登记-通过id删除")
	@RequiresPermissions("crm:c_payment_invoice:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		cPaymentInvoiceService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "收票登记-批量删除")
	@ApiOperation(value="收票登记-批量删除", notes="收票登记-批量删除")
	@RequiresPermissions("crm:c_payment_invoice:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.cPaymentInvoiceService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "收票登记-通过id查询")
	@ApiOperation(value="收票登记-通过id查询", notes="收票登记-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<CPaymentInvoice> queryById(@RequestParam(name="id",required=true) String id) {
		CPaymentInvoice cPaymentInvoice = cPaymentInvoiceService.getById(id);
		if(cPaymentInvoice==null || cPaymentInvoice.getDelFlag() != 0) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(cPaymentInvoice);
	}


	 @ApiOperation(value="拆票", notes="拆票")
	 @GetMapping(value = "/loadinvoice-split")
	 public Result<List<CPaymentInvoice>> loadinvoiceSplit(
			 @RequestParam(name="projectId",required=false) String projectId,
			 @RequestParam(name="subProjectId",required=false) String subProjectId,
			  @RequestParam(name="requestId",required=false,defaultValue = "0") String requestId

	 ) {
		 List<CPaymentInvoice> paymentInvoiceList = cPaymentInvoiceService.loadinvoiceSplit(projectId,subProjectId,requestId);
		 if(paymentInvoiceList==null) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(paymentInvoiceList);
	 }

    /**
    * 导出excel
    *
    * @param request
    * @param cPaymentInvoice
    */
    @RequiresPermissions("crm:c_payment_invoice:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, CPaymentInvoice cPaymentInvoice) {
        return super.exportXls(request, cPaymentInvoice, CPaymentInvoice.class, "收票登记");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequiresPermissions("crm:c_payment_invoice:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, CPaymentInvoice.class);
    }

}
